import jsYaml from "js-yaml";
import {statSync,readFileSync,createReadStream,
    writeFileSync,
    existsSync,
    watchFile,
    unwatchFile,
} from "fs";
import {resolve,sep} from "path";
import {createInterface} from "readline";
import os from "os";
import process from "node:process";



export function parseConfName() {
    let argvArr = Array.prototype.slice.call(process.argv);
    let nameFlag = "";
    if (argvArr.length < 3) {
        nameFlag = "test";
    } else {
        let targetStr = argvArr.find((item) => {
            return item.indexOf("conf=") > -1;
        });
        if (targetStr) {
            let targetName = targetStr.split("=")[1];
            nameFlag = `${targetName}`;
        } else {
            nameFlag = DefaultConf;
        };
        // console.log(nameFlag);

    }
    return nameFlag;
}


async function loadEnvApi(optType ="publish"){  //加载配置api
    let conf = parseConfName();
   
    let sourceFilePath = resolve(process.cwd(),conf+".yaml");
    try {
      
        let sourceStat = statSync(sourceFilePath);
        if(!sourceStat) return;    
       await wirteContent(sourceFilePath);

       if(optType == "development"){
        watchApiChange();
       }
       
    } catch (error) {
        // console.error(error)
        console.error(`加载api配置文件:${sourceFilePath}出错`);
        throw error;
    }
};


 function loadEnvContentWraper(){    //加载配置内容

    let cacheContent = null;

   return function(){
    if(cacheContent){
        return cacheContent;
    }
    let conf = parseConfName();
    let sourceFilePath = resolve(process.cwd(),conf+".yaml");
    try {
      
        let sourceStat = statSync(sourceFilePath);
        if(!sourceStat) return;    
        
        let resolveConfig = jsYaml.load(readFileSync(sourceFilePath, 'utf8'));
        cacheContent = resolveConfig;
        return resolveConfig;
    } catch (error) {
        // console.error(error)
        console.error(`加载api配置文件:${sourceFilePath}出错`);
        throw error;
    }
   }
}

//根据配置文件重写api/index
 async function wirteContent(sourceFilePath){
    await new Promise((reso,reject)=>{
        let content = "";
        const config = jsYaml.load(readFileSync(sourceFilePath, 'utf8'));
        if(!config.API){
            reject("当前环境下未发现 API配置");
        }
        let pathConfig = config.API;
        let targetPath = resolve(process.cwd(),"src/api/index.js");
        
    
        if(!existsSync(targetPath)){
            // createWriteStream()
            for(let key in pathConfig){
                content = content + `const ${key} = "${pathConfig[key]};"${os.EOL}`;
            }
            content =content + "export default {"+os.EOL+os.EOL;
            content += "};";
            writeFileSync(targetPath,content,{

            });
            reso();
        }else{      
            let pathkeys = Object.keys(pathConfig); 
            let targetSream =  createReadStream(targetPath);

            let ws = createInterface({
                input:targetSream,
            });
            ws.on("line",(inputStr)=>{

            let hitKey = pathkeys.find((keyItem)=>{
                    let reg = new RegExp("const "+keyItem,"g");
                    return reg.test(inputStr);
                });
                if(hitKey){
                    content = content +`const ${hitKey} = "${pathConfig[hitKey]}";${os.EOL}`;
                }else{
                    content =content+inputStr+os.EOL;
                }
            
            
                // console.log(input)
            });
            ws.on("close",()=>{
                let targetApiPath = resolve(process.cwd(),"src/api/api.ignore.js");
                writeFileSync(targetApiPath,content,{
                    flag:"w+"
                });
                reso();
            })
    };
    })
   
};


const loadEnvContent = loadEnvContentWraper();

/**
 * 
 * @returns 模块名称
 */
export function resoveModuleName(){
    let envContent = loadEnvContent();
    //有MODULE_NAME配置走配置
    if(envContent.MODULE_NAME){
        return envContent.MODULE_NAME;
    }else{
        let root = resolve(process.cwd());
        let pathArr = root.split(sep);
        return pathArr[pathArr.length-1];
    }
    
 };


 function watchApiChange(){
    let conf = parseConfName();
   
    let sourceFilePath = resolve(process.cwd(),conf+".yaml");
    let watchFilePath = resolve(process.cwd(),"src/api/index.js");
    const config = jsYaml.load(readFileSync(sourceFilePath, 'utf8'));
    let pathConfig = config.API;
    watchFile(watchFilePath,(cur,pre)=>{
        // console.log(cur);
        rewriteApi(pathConfig);
    });

    process.on("SIGINT",()=>{
        unwatchFile(watchFilePath);
        process.exit();
      
    });
 };


 function rewriteApi(pathConfig){
    let watchFilePath = resolve(process.cwd(),"src/api/index.js");
    let targetApiPath = resolve(process.cwd(),"src/api/api.ignore.js");
    let pathkeys = Object.keys(pathConfig); 
    let targetSream =  createReadStream(watchFilePath);
    let content = "";
    let ws = createInterface({
        input:targetSream,
    });
    ws.on("line",(inputStr)=>{

    let hitKey = pathkeys.find((keyItem)=>{
            let reg = new RegExp("const "+keyItem,"g");
            return reg.test(inputStr);
        });
        if(hitKey){
            content = content +`const ${hitKey} = "${pathConfig[hitKey]}";${os.EOL}`;
        }else{
            content =content+inputStr+os.EOL;
        }
    
    
        // console.log(input)
    });
    ws.on("close",()=>{
        writeFileSync(targetApiPath,content,{
            flag:"w+"
        });
    })
 }


export  {
    loadEnvApi,
    loadEnvContent,
};

